<template>
  <div class="main">
    <!-- :form="form" 必须优先注册 -->
    <a-form
      id="formLogin"
      class="user-layout-login"
      :form="form"
      ref="formLogin"
      @submit="handleSubmit"
    >
      <a-tabs
        :activeKey="activeKey"
        :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        @change="handleTabClick"
      >
        <a-tab-pane key="tab1" tab="Credentials">
          <a-alert
            v-if="isLoginError"
            type="error"
            style="margin-bottom:20px"
            showIcon
            message="用户名或密码错误" />
          <a-form-item>

            <a-input
              size="large"
              type="text"
              placeholder="用户名:Admin"
              v-decorator="[
                'username',
                {rules:[{required:true, message:'用户名为必填项目'},{validator:handleUsernameOrEmail}],validateTrigger:'change'}
              ]">
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"></a-icon>
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-input-password
              size="large"
              placeholder="密码:Admin"
              v-decorator="[
                'password',
                {rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}
              ]">
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input-password>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane key="tab2" tab="Mobil number">
          <a-form-item>
            <a-input
              type="text"
              size="large"
              placeholder="手机号"
              v-decorator="[
                'mobile',
                {rules: [{ required: true, pattern: /^1[34578]\d{9}$/, max:9, message: '手机号有误'}], validateTrigger: 'blur'}]">
              <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"></a-icon>
            </a-input>
          </a-form-item>
          <a-row class="pad0x-8" :style="{marginLeft:'-8px', marginRight:'-8px'}">
            <a-col :span="16" class="pad0x8">
              <a-form-item>
                <a-input
                  type="text"
                  size="large"
                  placeholder="验证码"
                  v-decorator="[
                    'captcha',
                    {rules: [{ required: true, message: '验证码不能为空' }], validateTrigger: 'blur'}]">
                  <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"></a-icon>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8" class="pad0x8">
              <a-button
                size="large"
                style="font-size:14px;"
                block
                tabindex="-1"
                :disabled="state.smsSendBtn"
                @click.stop.prevent="getCaptcha"
                v-text="!state.smsSendBtn && $t('user.register.get-verification-code') || (state.time+' s')"
              >
                {{ getCode }}
              </a-button>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>
      <a-form-item>
        <a-checkbox v-decorator="['remindme',{valuePropName:'checked'}]">{{ remindLogin }}</a-checkbox>
        <router-link to="{name:'recover', params:{ user: 'aaa'}}" :style="{ float: 'right' }">{{ forgetPW }}</router-link>
      </a-form-item>
      <a-form-item>
        <a-button
          class="login-button"
          type="primary"
          size="large"
          htmlType="submit"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
        >{{ btnLogin }}</a-button>
      </a-form-item>
      <div class="user-login-other">
        <span>{{ loginMethods }}</span>
        <a>
          <a-icon class="item-icon" type="alipay-circle"></a-icon>
        </a>
        <a>
          <a-icon class="item-icon" type="taobao-circle"></a-icon>
        </a>
        <a>
          <a-icon class="item-icon" type="weibo-circle"></a-icon>
        </a>
        <router-link class="register" :to="{ name: 'register' }">{{ registerTitle }}</router-link>
      </div>
    </a-form>
  </div>
</template>

<script>
 import md5 from 'md5'
// import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
 import { mapActions } from 'vuex'
 import { timeFix } from '@/utils/util'
// import { getSmsCaptcha, get2step } from '@/api/login'

export default {
  data () {
    return {
      activeKey: 'tab1',
      checked: false,
      loginMethods: '快捷登录方式',
      btnLogin: '登录',
      forgetPW: '忘记密码？',
      remindLogin: '记住我',
      getCode: '获取验证码',
      registerTitle: '注册',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this), // 创建form实例的方法
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    }
  },
  mounted () {
    console.log(this.form)
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    handleTabClick (key) {
      this.activeKey = key
    },
    handleUsernameOrEmail (rule, value, callback) {
      // const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        this.state.loginType = 0
      } else {
        this.state.loginType = 1
      }
      callback() // callback有什么用
    },
    handleSubmit (e) {
      debugger
      e.preventDefault()
      const {
        // 引用form对象的validateFields方法
        // 校验并获取一组输入域的值与 Error，若 fieldNames 参数为空，则校验全部组件
        // Function([fieldNames: string[]], [options: object], callback: Function(errors, values))
        form: { validateFields },
        state,
        activeKey,
        Login
      } = this
      state.loginBtn = true
      const validateFieldsKey = activeKey === 'tab1' ? ['username', 'password'] : ['mobile', 'captcha']
      console.log('validateFieldsKey', validateFieldsKey)
      // { force: true }对已经校验过的表单域，在 validateTrigger 再次被触发时是否再次校验
      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          console.log('login form', values)
          const loginParams = { ...values }
          console.log('loginParams', loginParams)
          delete loginParams.username
          loginParams[!state.loginType ? 'email' : 'username'] = values.username
          loginParams.password = md5(values.password)
          debugger
          Login(loginParams)
            .then((res) => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    loginSuccess (res) {
      console.log(res)
      // check res.homePage define, set $router.push name res.homePage
      // Why not enter onComplete
      /*
      this.$router.push({ name: 'analysis' }, () => {
        console.log('onComplete')
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      })
      */
      this.$router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      this.isLoginError = false
    },
    requestFailed (err) {
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  }
}
</script>

<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }
  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
.pad0x8{
  padding-left:8px;
  padding-right:8px;
}

// .pad0x-8{
//   padding-left:-8px;
//   padding-right:-8px;
// }
</style>
